<?php

namespace Portal\ContractBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Portal\ContractBundle\Entity\Contract;
use Portal\NotificationBundle\Entity\Notification;
use Portal\ContractBundle\Entity\Invoice;

class ContractController extends Controller
{

  private $activeStatus = "('created')";
  private $availableStatus = "('created', 'complete', 'userDenied', 'started')";
//  private $nextStatus = 'Сурагч зөвшөөрөх';
  
  public function newAction(Request $request, $lessonId)
  {
    $lesson = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:Lesson')->find($lessonId);
    if (!$lesson) {
      $this->get('session')->setFlash('error', 'Уучлаарай энэ хичээл олдохгүй байна.');
      return new RedirectResponse($request->headers->get('referer'));
    }

    return $this->render('PortalContractBundle:Contract:new.html.twig', array(
        'lesson' => $lesson,
        'lessonId' => $lessonId,
        'studentId' => $lesson->getUser()->getId(),
        ));
  }

  public function createAction(Request $request)
  {
    $tutor = $this->checkUser();

    if ($request->getMethod() != 'POST') {
      $this->get('session')->setFlash('error', 'Зөвшөөрөгдөөгүй хандалт!');
      return $this->redirect($this->generateUrl('logout'));
    }

    // GET POST VALUES
    $postValues = $request->request;

    $lessonId = $postValues->get('lessonId');
    // CHECK CONTRACT IS CREATED BY THIS LESSON_ID
    if ($this->checkContractIsCreated($lessonId) == true) {
      $this->get('session')->setFlash('error', 'Уучлаарай энэ хичээлийн хуваариар гэрээ үүсгэгдсэн байна!');
      return new RedirectResponse($request->headers->get('referer'));
    }
    // COLLECT PARAMS
    $studentId = $postValues->get('studentId');
    $content = $postValues->get('content');

    // GET LESSON
    $lesson = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:Lesson')->find($lessonId);
    // GET STUDENT
    $student = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:User')->find($studentId);

    // SET PARAMS TO CONTRACT
    $contract = new Contract();
    $contract->setLesson($lesson);
    $contract->setTutorId($tutor->getId());
    $contract->setUser($student);
    $contract->setContent($content);
    $contract->setStatus($this->container->getParameter('contractStatusCreated'));
    $contract->setCreatedAt(new \DateTime());
    $contract->setUpdatedAt(new \DateTime());
    $contract->setTutorFlag($this->container->getParameter('contractTutorFlagYes'));
    $contract->setCreatedIp($_SERVER['REMOTE_ADDR']);
    $contract->setIsActive($this->container->getParameter('statusActive'));
    // SAVE CONTRACT
    $em = $this->getDoctrine()->getManager();
    $em->persist($contract);
    $em->flush();

    
    $lessonStatus = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:LessonStatus')->find($this->container->getParameter('lessonStatusContracted'));
    $lesson->setStatus($lessonStatus);
    $em = $this->getDoctrine()->getManager();
    $em->persist($lesson);
    $em->flush();
    
    // ADD NOTIFICATION
    $this->createContractAddNotification($contract->getId());
    
    
    // SHOW
    $this->get('session')->setFlash('notice', 'Гэрээ амжилттай үүсгэлээ');
    return $this->redirect($this->generateUrl('homepage'));
  }

  public function showAction($contractId, $notificationId = null)
  {
    $contract = $this->checkContractIsLegal($contractId,$this->availableStatus);
    
    if ($contract == false) {
      $this->get('session')->setFlash('error', 'Уучлаарай энэ гэрээ танд ирээгүй байна!');
      return $this->redirect($this->generateUrl('homepage'));
    }

    if(isset($notificationId))
    {
      $this->showNotification($notificationId);
    }
    
    if($contract['STATUS'] == $this->container->getParameter('contractStatusCreated'))
    {      
      $block = null;
    }else if ($contract['STATUS'] == $this->container->getParameter('contractStatusComplete')){
      $block = 1;
    }else{
      $block = 2;
    }
    
    return $this->render('PortalContractBundle:Contract:show.html.twig', array(
        'contractId' => $contract['ID'],
        'currentStatus' => $contract['STATUS'],
        
        'contractHTML' => $contract['CONTENT'],
        'block' => $block
        ));
  }

  public function showContractByComponentAction($contractId)
  {
    $contract = $this->checkContractIsLegal($contractId, $this->availableStatus);
    if ($contract == false) {
      $this->get('session')->setFlash('error', 'Уучлаарай энэ гэрээ танд ирээгүй байна!');
      return $this->redirect($this->generateUrl('homepage'));
    }
    
    return $this->render('PortalContractBundle:Contract:showContractByComponent.html.twig', array(
                'currentStatus' => $contract['STATUS'],
                //'nextStatus' => $this->nextStatus,
                'contractHTML' => $contract['CONTENT'],
                'contractId' => $contractId
            ));
  }
  
  public function userSubmitAction(Request $request)
  {
    if ($request->getMethod() != 'POST') {
      $this->get('session')->setFlash('error', 'Зөвшөөрөгдөөгүй хандалт!');
      return $this->redirect($this->generateUrl('logout'));
    }
    
    // GET POST VALUES
    $postValues = $request->request;    
    $contractId = $postValues->get('contractId');
    $contractContent= $postValues->get('contractContent');
    
    if(strlen(trim($contractContent)) == 0)
    {
      $this->get('session')->setFlash('error', 'Гэрээ буруу байна!');
      return $this->redirect($this->generateUrl('homepage'));
    }
    
    
    // CRETERIA
    $contract = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:Contract')->findBy(array('id' => $contractId, 'isActive' => $this->container->getParameter('statusActive')));
    
    // CHECK CONTRACT
    if(!$contract)
    {
      $this->get('session')->setFlash('error', 'Уучлаарай энэ гэрээ байхгүй байна!');
      return $this->redirect($this->generateUrl('logout'));
    }
    
    $contract = $contract[0];
    
    // CHECK CONTRACT IS LEGAL
    $contractCheck = $this->checkContractIsLegal($contractId, $this->activeStatus);
    if ($contractCheck == false) {
      $this->get('session')->setFlash('error', 'Уучлаарай энэ гэрээ танд ирээгүй байна!');
      return $this->redirect($this->generateUrl('homepage'));
    }
    
    if($this->checkInvoiceForThisContract($contractId) == true )
    {
      $this->get('session')->setFlash('error', 'Уучлаарай энэ гэрээгээр нэхэмжлэх үүссэн байна та админд хандана уу!');
      return $this->redirect($this->generateUrl('homepage'));
    }
    
    if(isset($_POST['agree'])){
      
      $contract->setContent($contractContent);
      $contract->setStatus($this->container->getParameter('contractStatusComplete'));
      $contract->setUserFlag($this->container->getParameter('contractUserFlagYes'));      
      $em = $this->getDoctrine()->getManager();
      $em->persist($contract);
      $em->flush();
      
      // CREATE INVOICE
      $invoiceId = $this->createInvoice($contract);      
      
      // CREATE NOTIFICATION
      $this->compeleteContractAddNotificationForInvoice($invoiceId);
      
      $this->compeleteContractAddNotification($contract->getId());
      
      if ($contract->getId()) {
        $this->get('session')->setFlash('notice', 'Хичээл заалгах гэрээг зөвшөөрлөө');
        return $this->redirect($this->generateUrl('homepage'));
      }
      
    }elseif(isset($_POST['disagree'])){
      
      // SET CONTRACT STATUS TO USER DENIED
      $contract->setStatus($this->container->getParameter('contractStatusUserDenied'));
      $contract->setUserFlag($this->container->getParameter('contractUserFlagNo'));
      $contract->setIsActive($this->container->getParameter('statusInActive'));
      $em = $this->getDoctrine()->getManager();
      $em->persist($contract);
      $em->flush();
      
      // SET LESSON STATUS TO USER DENIED
      $lesson = $contract->getLesson();
      $lessonStatus = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:LessonStatus')->find($this->container->getParameter('lessonStatusUserDenied'));
      $lesson->setStatus($lessonStatus);
      $em = $this->getDoctrine()->getManager();
      $em->persist($lesson);
      $em->flush();
      
      

      if ($contract->getId()) {
        $this->get('session')->setFlash('notice', 'Хичээл заалгах гэрээг цуцаллаа');
        return $this->redirect($this->generateUrl('homepage'));
      }
    }else{
      $this->get('session')->setFlash('error', 'Зөвшөөрөгдөөгүй хандалт!');
      return $this->redirect($this->generateUrl('logout'));
    }
    
  }
  
  private function lessonRoleBackAction($lessonId)
  {
    $lesson = $this->getDoctrine()->getEntityManager()->getRepository('PortalLessonBundle:Lesson')->find($lessonId);
    if($lesson)
    {
      $lesson->setStatus();
      $em = $this->getDoctrine()->getManager();
      $em->persist($lesson);
      $em->flush();
    }
  }

  private function checkUser()
  {
    $user = $this->container->get('security.context')->getToken()->getUser();

    if ($user) {
      if (!is_object($user)) {
        header('Location: /logout');
        die;
      }

      if (is_array($user->getRoles()) == FALSE) {
        header('Location: /logout');
        die;
      }

      return $user;
    } else {
      header('Location: /logout');
      die;
    }
  }

  private function showNotification($notificationId)
  {
    $notification = $this->getDoctrine()->getEntityManager()->getRepository('PortalNotificationBundle:Notification')->find($notificationId);
    if($notification)
    {
      
      
      $user = $this->checkUser();
      if (in_array($this->container->getParameter('ROLE_USER'), $user->getRoles())) {
        $notification->setStatus($this->container->getParameter('notificationStatusRead'));
      }else if (in_array($this->container->getParameter('ROLE_TUTOR'), $user->getRoles())) {
        $notification->setStatusTutor($this->container->getParameter('notificationStatusRead'));
      }
      // SAVE CONTRACT
      $em = $this->getDoctrine()->getManager();
      $em->persist($notification);
      $em->flush();
      
      return true;
    }
  }


  private function checkContractIsCreated($lessonId)
  {
    $contractIsActive = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:Contract')->getContractIsActiveForLesson($lessonId);    
    if ($contractIsActive) {
      if($contractIsActive == $this->container->getParameter('statusInActive'))
      {
        return false;  
      }else{
        return true;
      }
    } else {
      return false;
    }
  }

  private function checkContractIsLegal($contractId, $status)
  {
    $user = $this->checkUser();
    if (in_array($this->container->getParameter('ROLE_USER'), $user->getRoles())) {
      $userRole = 'ROLE_USER';
    } else if (in_array($this->container->getParameter('ROLE_TUTOR'), $user->getRoles())) {
      $userRole = 'ROLE_TUTOR';
    } else {
      return false;
    }
    
    $contract = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:Contract')->checkThisContractIsLegal($contractId, $status, $userRole, $user->getId());
    
    if ($contract) {
      return $contract;
    } else {
      return false;
    }
  }
  
  private function createContractAddNotification($contractId)
  {
    $user = $this->checkUser();

    $contract = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:Contract')->find($contractId);
    
    $notificationType = $this->container->getParameter('notificationContract');
    $toUrl = $this->container->getParameter('notificationUrlContract') . $contractId;
    $tableId = $contractId;
    $description = 'Таны хичээлийн хуваарийн дагуу "" гэрээ үүсгэлээ.';    
    $tutorId = $contract->getLesson()->getTutor()->getId();
    $userId = $contract->getLesson()->getUser()->getId();
    $status = $this->container->getParameter('notificationStatusUnread');
    $isActive = $this->container->getParameter('statusActive');
    $createdAt = new \DateTime();

    $lastInsertedId = $this->saveNotification($notificationType, $tableId, $toUrl, $description, $tutorId, $userId, $status, $isActive, $createdAt, 'ROLE_USER');

    return $lastInsertedId;
  }
  
  private function compeleteContractAddNotification($contractId)
  {
    $user = $this->checkUser();

    $contract = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:Contract')->find($contractId);

    $notificationType = $this->container->getParameter('notificationContract');
    $toUrl = $this->container->getParameter('notificationUrlContract') . $contractId;
    $tableId = $contractId;
    $description = 'Таны үүсгэсэн "" гэрээг сурагч зөвшөөрлөө.';
    $tutorId = $contract->getLesson()->getTutor()->getId();
    $userId = $contract->getLesson()->getUser()->getId();
    $status = $this->container->getParameter('notificationStatusUnread');
    $isActive = $this->container->getParameter('statusActive');
    $createdAt = new \DateTime();

    $lastInsertedId = $this->saveNotification($notificationType, $tableId, $toUrl, $description, $tutorId, $userId, $status, $isActive, $createdAt, null, $this->container->getParameter('contractDirectionToTutor'));

    return $lastInsertedId;
  }


  private function compeleteContractAddNotificationForInvoice($invoiceId)
  {
    $user = $this->checkUser();

    $invoice = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:Invoice')->find($invoiceId);

    $notificationType = $this->container->getParameter('notificationInvoice');
    $toUrl = $this->container->getParameter('notificationUrlInvoice') . $invoiceId;
    $tableId = $invoiceId;
    $description = 'Танд "'.$invoice->getContract()->getLesson()->getSubject()->getName().'" хичээл дээр төлбөрийн нэхэмжлэх ирсэн байна.';    
    $tutorId = $invoice->getContract()->getLesson()->getTutor()->getId();
    $userId = $invoice->getContract()->getLesson()->getUser()->getId();
    $status = $this->container->getParameter('notificationStatusUnread');    
    $isActive = $this->container->getParameter('statusActive');
    $createdAt = new \DateTime();

    $lastInsertedId = $this->saveNotification($notificationType, $tableId, $toUrl, $description, $tutorId, $userId, $status, $isActive, $createdAt, $this->container->getParameter('contractDirectionToUser'));

    return $lastInsertedId;
  }

  /**
   * Notification хадгалах
   * 
   * @param type $noificationType
   * @param type $tableId
   * @param type $toUrl
   * @param type $description
   * @param type $tutorId
   * @param type $userId
   * @param type $status
   * @param type $isActive
   * @param type $createdAt
   */
  private function saveNotification($notificationType, $tableId, $toUrl, $description, $tutorId, $userId, $status, $isActive, $createdAt, $userRole = null, $tutorRole = null)
  {
    $notification = new Notification();
    $notification->setNotificationType($notificationType);
    $notification->setTableId($tableId);
    $notification->setToUrl($toUrl);
    $notification->setDescription($description);
    $notification->setTutorId($tutorId);
    $notification->setUserId($userId);    
    $notification->setIsActive($isActive);
    $notification->setCreatedAt($createdAt);
    $notification->setUpdatedAt(new \DateTime());
    if(isset($userRole))
    {
      $notification->setUserShowPermission($this->container->getParameter('contractDirectionToUser'));
      $notification->setStatus($status);
    }
    
    if(isset($tutorRole))
    {
      $notification->setTutorShowPermission($this->container->getParameter('contractDirectionToTutor'));
      $notification->setStatusTutor($status);
    }
    
    $em = $this->getDoctrine()->getManager();
    $em->persist($notification);
    $em->flush();

    return $notification->getId();
  }
  
  
  private function createInvoice($contract)
  {
    if($contract) {     
      $totalAmout = $this->getTotalAmount($contract, $this->container->getParameter('lessonStatusContracted'));
      $content = $this->generateInvoiceContent($contract);
      
      $invoice = new Invoice();
      $invoice->setContract($contract);
      $invoice->setAmount($totalAmout);
      $invoice->setContent($content['content']);
      $invoice->setTemplateId($content['templateId']);
      $invoice->setIsCompleted($this->container->getParameter('statusInActive'));
      $invoice->setUser($contract->getUser());      
      $invoice->setIsActive($this->container->getParameter('statusActive'));
      $invoice->setCreatedAt(new \DateTime());      
      $em = $this->getDoctrine()->getManager();
      $em->persist($invoice);
      $em->flush();
             
      if($invoice->getId())
      {
        return $invoice->getId();
      }else{
        return null;
      }
    }else{
      return null;
    }
  }
  
  private function getTotalAmount($contract, $lessonStatus)
  {
    $lessonId = (int) $contract->getLesson()->getId();
    $lessonObject = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:Lesson')->findBy(array('id' => $lessonId, 'status' => $lessonStatus, 'isActive' => $this->container->getParameter('statusActive')));
    
    $lesson = $lessonObject[0];
    
    $totalHours = $lesson->getTotalHours();
    $hourlyFee = $lesson->getHourlyFee();
    $totalAmount = $totalHours * $hourlyFee;
    
    return $totalAmount;
    
  }
  
  private function generateInvoiceContent($contract)
  {
    $content = 'Invoice - н content';
    $templateId = 1;
    
    $invoiceContent = array('content' => $content, 'templateId' => $templateId);
    
    return $invoiceContent;
  }

  private function checkInvoiceForThisContract($contractId)
  {
    $invoiceId = $this->getDoctrine()->getEntityManager()->getRepository('PortalContractBundle:Invoice')->findInvoiceByContractId($contractId);
    
    if($invoiceId)
    {
      return true;
    }else{
      return false;
    }
  }

}
